<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import echarts, { ECOption } from './config'

const chartRef = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null
let resizeObserver: ResizeObserver | null = null

const props = defineProps({
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '100%'
	},
	data: {
		type: Object,
		default: () => ({
			text: '',
			years: [],
			theoryTotals: [],
			practiceTotals: []
		})
	}
})

// 监视数据变化
watch(
	() => props.data,
	(newVal) => {
		if (myChart && chartRef.value) {
			updateChart()
		}
	},
	{ deep: true }
)

// 定义配置对象
const lineOption = computed((): ECOption => {
	return {
		// title: {
		// 	text: '成绩走势',
		// 	left: 'center',
		// 	top: '0',
		// 	textStyle: {
		// 		color: '#409eff',
		// 		fontSize: 18
		// 	}
		// },
		tooltip: {
			trigger: 'axis'
		},
		legend: {
			data: ['理论总分', '实践总分'],
			icon: 'circle',
			right: 'right'
		},
		grid: {
			left: '50',
			right: '90',
			bottom: '25',
			top: '50'
		},
		xAxis: {
			name: '学年',
			type: 'category',
			data: props.data?.years || []
		},
		yAxis: {
			name: '总分',
			type: 'value'
		},
		series: [
			{
				name: '理论总分',
				data: props.data?.theoryTotals || [],
				type: 'line',
				label: {
					show: true,
					position: 'top',
					fontSize: '16'
				},
				lineStyle: {
					width: 3,
					color: '#409eff'
				},
				itemStyle: {
					color: '#409eff'
				}
			},
			{
				name: '实践总分',
				data: props.data?.practiceTotals || [],
				type: 'line',
				label: {
					show: true,
					position: 'top',
					fontSize: '16'
				},
				lineStyle: {
					width: 3,
					color: '#67c23a'
				},
				itemStyle: {
					color: '#67c23a'
				}
			}
		]
	}
})

// 定义样式对象
const echartsStyle = computed(() => ({
	width: props.width,
	height: props.height
}))

// 初始化图表
function initChart() {
	if (!chartRef.value) return

	// 避免重复初始化
	if (myChart) {
		myChart.dispose()
	}

	myChart = echarts.init(chartRef.value)
	updateChart()

	// 监听容器大小变化
	if (resizeObserver) {
		resizeObserver.disconnect()
	}

	resizeObserver = new ResizeObserver(() => {
		myChart?.resize()
	})

	resizeObserver.observe(chartRef.value)
}

// 更新图表
function updateChart() {
	if (!myChart) return
	myChart.setOption(lineOption.value, true)
}

onMounted(() => {
	// 延迟初始化确保DOM已渲染
	setTimeout(() => {
		initChart()
	}, 50)

	// 窗口大小改变时重绘图表
	window.addEventListener('resize', () => {
		myChart?.resize()
	})
})

// 组件卸载时释放资源
onUnmounted(() => {
	if (resizeObserver) {
		resizeObserver.disconnect()
		resizeObserver = null
	}

	window.removeEventListener('resize', () => {
		myChart?.resize()
	})

	if (myChart) {
		myChart.dispose()
		myChart = null
	}
})
</script>

<template>
	<div ref="chartRef" :style="echartsStyle"></div>
</template>

<style scoped>
div {
	width: 100%;
	height: 100%;
}
</style>
